const { desktopCapturer, ipcRenderer } = require('electron');//获取桌面流的信息
const EventEmitter = require('events');
const peer = new EventEmitter();
const video = document.getElementById('screen-video');
function play(stream) {
    video.srcObject = stream;
    video.onloadedmetadata = () => video.play()
}
peer.on('add-stream', (stream) => {
    console.log('play stream', stream);
    play(stream);
});


//创建一个远程连接
const pc = new window.RTCPeerConnection({})
async function createOffer() {//创造一个远程端点
    const offer = await pc.createOffer({//只需要视频
        offerToReceiveAudio: false,
        offerToReceiveVideo: true,
    })
    await pc.setLocalDescription(offer);
    console.log('pc offer', JSON.stringify(offer))
    return pc.localDescription
}
createOffer();
async function setRemote(answer) {//设置远程SDP
    await pc.setRemoteDescription(answer)
}
window.setRemote = setRemote;//为了在控制台的能看看到效果
pc.onaddstream = function (e) {//监听媒体流的增加
    console.log('add-stream', e)
    peer.emit('add-stream', e.stream)
}

pc.onicecandidate = function (e) {//触发此事件函数
    console.log('candidate', JSON.stringify(e.candidate))
}

let candidates = [];
async function addIceCandidate(candidate) {//接收信号
    if (candidate) {//可能结果为null
        candidates.push(candidate);
    }
    if (pc.remoteDescription && pc.remoteDescription.type) {
        //pc.remoteDescription描述了和远程对端之间的会话(包括配置和媒体信息) ，如果还没有被设置过的话，它会是 null.
        for (var i = 0; i < candidates.length; i++) {
            await pc.addIceCandidate(new RTCIceCandidate(candidates[i]))
        }
        candidates = [];//清空数据
    }
}
window.addIceCandidate = addIceCandidate;//方便在控制台上操作